package com.dq.component;

import com.dq.mapper.UserMapper;
import com.dq.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;



@Component
public class CustomSavedRequestAwareAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    UserMapper userMapper;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws ServletException, IOException {
        RequestCache requestCache = new HttpSessionRequestCache();
        SavedRequest savedRequest = requestCache.getRequest(httpServletRequest,httpServletResponse);
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        User user = null;
        try {
            user = userMapper.getUserById(userDetails.getUsername());
            httpServletRequest.getSession().setAttribute("userId",user.getId());
        }catch (Exception e){
            e.printStackTrace();
        }
        if(savedRequest != null){
            //url = savedRequest.getRedirectUrl();
        }else{
            getRedirectStrategy().sendRedirect(httpServletRequest,httpServletResponse,"/");
        }
        super.onAuthenticationSuccess(httpServletRequest, httpServletResponse, authentication);
    }
}
